<template>
    <div>
        <a-modal title="添加需求" :bodyStyle="{ padding: '12px 24px', height: '600px', overflow: 'hidden' }" centered v-model:visible="visible" :confirm-loading="loading" :width="1000" okText="保存" @ok="handleSave" @cancel="handleCancel">
            <div style="padding-left: 12px">
                <flexbox v-show="searchType === 1">
                    <h-dic-select radio v-model:value="form.projectKeyOrId" title="项目" :disabled="projectDisabled" :defaultOptions="projectOptions" @change="handleChange($event, 'pro')" />
                    <h-dic-select radio v-model:value="form.component" title="模块" :disabled="componentDisabled" :defaultOptions="componentsOptions" class="margin-l-8" @change="handleChange($event, 'component')" />
                    <h-dic-select :defaultOptions="issueTypeOptions" class="margin-l-8" title="类型" @change="handleChange($event, 'issueType')" />
                    <h-dic-select :defaultOptions="issueStatusOptions" class="margin-l-8" title="状态" @change="handleChange($event, 'issueStatus')" />
                    <HSuggestInput class="cell-item margin-l-8" allowClear placeholder="请输入环境关键字" v-model:value="form.environment" style="max-width: 200px; margin-bottom: 0" @change="handleSearch" />
                </flexbox>
                <flexbox :class="searchType === 1 ? 'margin-t-8' : ''">
                    <!-- <a-input class="cell-item margin-l-8" allowClear placeholder="请输入环境关键字" v-model:value="form.name" style="min-width: 100px" /> -->
                    <a-input class="cell-item margin-l-8" allowClear placeholder="请输入issue名称" v-model:value="form.name" style="min-width: 300px; margin-bottom: 0" v-show="searchType === 1" />
                    <flexbox v-show="searchType === 2">
                        <a-input class="cell-item margin-l-8" allowClear placeholder="请按照jira语法输入" v-model:value="form.jql" style="min-width: 610px" />
                    </flexbox>
                    <flexbox v-show="searchType === 3">
                        <a-input class="cell-item margin-l-8" allowClear placeholder="请输入issue关键字" v-model:value="form.issueKey" style="min-width: 610px; margin-bottom: 0" />
                    </flexbox>
                    <flexbox style="flex-shrink: 0">
                        <a-button type="primary" @click="handleSearch">搜索</a-button>
                        <a-tooltip title="切换到使用JQL的高级搜索" v-if="searchType === 1">
                            <a class="margin-l-8" @click="handleChangeType(2)">高级</a>
                        </a-tooltip>
                        <a-tooltip title="切换到基本搜索" v-else>
                            <a class="margin-l-8" @click="handleChangeType(1)">简单</a>
                        </a-tooltip>
                        <a-tooltip title="切换到issue查询">
                            <a class="margin-l-8" @click="handleChangeType(3)">issue key查询</a>
                        </a-tooltip>
                    </flexbox>
                </flexbox>
            </div>
            <a-divider style="margin: 12px 0" />
            <CustomTable autoResize rowKey="id" size="small" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :columns="columns" :data-source="list" :pagination="paginationConfig" @change="handleTableChange" />
        </a-modal>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import store from '@/store';
import { useSearchHistory } from '@/hooks/common/useSearchHistory';
import { message } from 'ant-design-vue/es';
import { CustomTable, HCustomSelect, HDicSelect, HShowMoreSelect, HRangePickerCell, HSuggestInput } from '@/components';
import { useTableRowSelect } from '@/components/Table/hooks/index';
import { defineComponent, reactive, toRefs } from 'vue';
export default defineComponent({
    components: {
        HCustomSelect,
        HDicSelect,
        HShowMoreSelect,
        HRangePickerCell,
        CustomTable,
        HSuggestInput
    },
    emits: ['success'],
    setup(props, { emit }) {
        const { saveHistory } = useSearchHistory();
        const { selectedRowKeys, allSelectedRows, onSelectChange, setSelectRows } = useTableRowSelect();
        const columns = [
            {
                title: '关键字',
                dataIndex: 'issueKey'
            },
            {
                title: '名称',
                dataIndex: 'summary'
            },
            {
                title: '类型',
                dataIndex: 'issueType'
            },
            {
                title: '状态',
                dataIndex: 'status'
            }
        ];
        const state = reactive<any>({
            form: {
                projectKeyOrId: null,
                issueTypeIds: null,
                issueStatusIds: null,
                component: '', // 模块
                environment: '', // 环境
                jql: '', //输入高级查询方式
                name: '',
                issueKey: ''
            },
            list: [],
            visible: false,
            detail: {},
            type: 1,
            excludeJiraIds: '',
            loading: false,
            searchType: 1,
            projectOptions: [],
            componentsOptions: [],
            issueTypeOptions: [],
            issueStatusOptions: [],
            paginationConfig: {
                total: 0,
                pageSize: 20, // 每页中显示10条数据
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '15', '20'], // 每页中显示的数据
                showTotal: (total: number) => `共有 ${total} 条数据`, // 分页中显示总的数据
                current: 1
            },
            saveQuery: {}, //保存参数
            jiraInfo: null,
            projectDisabled: false,
            componentDisabled: false
        });
        const handleReset = () => {
            state.form = {
                projectKeyOrId: null,
                issueTypeIds: null,
                issueStatusIds: null,
                jql: '', //输入高级查询方式
                name: '',
                issueKey: ''
            };
            state.searchType = 1;
            setSelectRows([], []);
            state.list = [];
        };
        const getJiraInfo = async () => {
            const query = {
                id: state.detail.system
            };
            const { success, moule } = await api.jiraModel.findBySystemId(query);
            if (success) {
                state.jiraInfo = moule;
            }
        };
        const open = async (detail, saveQuery = {}) => {
            handleReset();
            state.detail = {
                ...detail
            };
            state.saveQuery = {
                ...saveQuery
            };
            const success = await getProjectOptions();
            if (success) {
                // 获取jira信息
                if (!state.jiraInfo) {
                    await getJiraInfo();
                }
                // 有jira信息项目后继续获取模块信息
                if (state.jiraInfo.projectKey) {
                    state.form.projectKeyOrId = state.jiraInfo.projectKey;
                    state.projectDisabled = !!state.form.projectKeyOrId;
                    state.componentDisabled = !!state.jiraInfo.componentId;
                    state.form.component = state.jiraInfo.componentId;
                    getComponentsOptions();
                }
                // 获取类型
                getIssueTypeOptions();
                // 获取状态
                getIssueStatusOptions();

                let idArr = [];
                if (state.detail.pmpJiraIssueDTOs && state.detail.pmpJiraIssueDTOs.length) {
                    const arr = state.detail.pmpJiraIssueDTOs.map((item) => item.id);
                    idArr = idArr.concat(arr);
                }
                if (idArr.length) {
                    state.excludeJiraIds = idArr.join(',');
                } else {
                    state.excludeJiraIds = '';
                }
                getList();
                state.visible = true;
            }
        };
        const handleSave = async () => {
            if (!allSelectedRows.value.length) {
                message.error('请勿提交空数据');
                return;
            }
            state.loading = true;
            const query = allSelectedRows.value.map((item) => ({
                issueId: item.id,
                component: item.component,
                projectKey: item.projectKey,
                operation: 'add',
                versionId: state.detail.id,
                catalogCode: state.detail.pmpProductDetailDTO.catalogCode,
                ...state.saveQuery
            }));
            const { success, errorMsg } = await api.jiraIssueModel.batchDeal(query);
            if (success) {
                state.visible = false;
                message.success('添加成功');
                emit('success');
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
        };
        const handleCancel = () => {
            state.visible = false;
        };

        const getProjectOptions = async () => {
            const query = {
                systemId: state.detail.system
            };
            const { success, moule, errorMsg } = await api.jiraModel.getAllProjectsFromJira(query);
            if (success) {
                state.projectOptions = [...moule];
            } else {
                message.error(errorMsg);
            }
            return success;
        };
        const getComponentsOptions = async () => {
            const query = {
                url: state.jiraInfo.url,
                empId: store.getters.userInfo.employeeDTO.empId,
                projectCode: state.form.projectKeyOrId
            };
            const { success, moule } = await api.jiraModel.getComponents(query);
            if (success) {
                state.componentsOptions = [...moule];
            }
        };
        const getIssueTypeOptions = async () => {
            const query = {
                systemId: state.detail.system,
                projectKeyOrId: state.form.projectKeyOrId
            };
            const { success, moule } = await api.jiraModel.getIssueTypesFromJira(query);
            if (success) {
                state.form.issueTypeIds = null;
                // 过滤测试issue类型
                state.issueTypeOptions = moule.filter((item) => !['测试', '子任务'].includes(item.name));
            }
        };
        const getIssueStatusOptions = async () => {
            const query = {
                systemId: state.detail.system,
                projectKeyOrId: state.form.projectKeyOrId,
                issueTypeIds: state.form.issueTypeIds
            };
            const { success, moule } = await api.jiraModel.getIssueStatusesFromJira(query);
            if (success) {
                state.issueStatusOptions = [...moule];
            }
        };
        const getList = async () => {
            const { current, pageSize } = state.paginationConfig;
            if (state.form.environment) {
                saveHistory(state.form.environment);
            }
            const query = {
                empId: store.getters.userInfo.employeeDTO.empId,
                systemId: state.detail.systemId || state.detail.system,
                excludeJiraIds: state.excludeJiraIds,
                ...state.form,
                pageSize,
                pageNum: current
            };
            const { success, moule, errorMsg, totalCount } = await api.jiraModel.getIssuesByConditions(query);
            if (success) {
                // 过滤测试issue类型
                state.list = moule.filter((item) => item.issueType !== '测试');
                state.paginationConfig.total = totalCount;
            } else {
                message.error(errorMsg);
            }
        };
        const handleChange = (val, field) => {
            if (field === 'pro') {
                state.form.projectKeyOrId = val ? val.id : null;
                getComponentsOptions();
                getIssueTypeOptions();
                getIssueStatusOptions();
            }
            if (field == 'issueType') {
                state.form.issueTypeIds = val;
                state.form.issueStatusIds = null;
                getIssueStatusOptions();
                if (val == 1) {
                    state.form.environment = '生产';
                }
            }
            if (field === 'issueStatus') {
                state.form.issueStatusIds = val;
            }
            if (field === 'component') {
                state.form.component = val ? val.id : null;
            }
            handleSearch();
        };
        const handleChangeType = (type) => {
            state.searchType = type;
        };

        const handleTableChange = (val) => {
            state.paginationConfig = val;
            getList();
        };

        const handleSearch = () => {
            state.paginationConfig.current = 1;
            getList();
        };

        return {
            columns,
            ...toRefs(state),
            open,
            handleSave,
            handleCancel,
            onSelectChange,
            getProjectOptions,
            handleChange,
            getList,
            handleSearch,
            handleChangeType,
            handleTableChange,
            selectedRowKeys,
            getComponentsOptions
        };
    }
});
</script>

<style scoped lang="less">
.cell-item {
    font-size: 14px;
    cursor: pointer;
    color: #344563;
    margin-right: 8px;
}
::v-deep(.ant-table-body) {
    max-height: 405px !important;
}
</style>